<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ disabled: disableSubmit }"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top: 20px">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- 基本信息 -->
        <a-card title="基本信息" size="small" style="margin-bottom: 16px;">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="出库单号">
                <a-input v-decorator="['outboundNo']" placeholder="系统自动生成" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="出库日期">
                <j-date
                  v-decorator="['outboundDate', {rules: [{required: true, message: '请选择出库日期!'}]}]"
                  :showTime="true"
                  dateFormat="YYYY-MM-DD"
                  placeholder="请选择出库日期"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item label="备注">
                <a-textarea
                  v-decorator="['remark']"
                  :rows="2"
                  placeholder="请输入备注信息"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <!-- 物料信息 -->
        <a-card title="物料信息" size="small" style="margin-bottom: 16px;">
          <div class="table-operator" style="margin-bottom: 16px;">
            <a-button-group>
              <a-button type="primary" @click="handleAddMaterial('1')" icon="profile">
                添加型材
              </a-button>
              <a-button type="primary" @click="handleAddMaterial('2')" icon="tool">
                添加配件
              </a-button>
              <a-button type="primary" @click="handleAddMaterial('3')" icon="experiment">
                添加辅件
              </a-button>
              <a-button type="primary" @click="handleAddMaterial('4')" icon="appstore">
                添加其他
              </a-button>
              <a-button type="primary" @click="handleAddMaterial('5')" icon="scissor">
                添加余料
              </a-button>
              <a-button type="primary" @click="handleAddMaterial('6')" icon="gold">
                添加半料
              </a-button>
            </a-button-group>
            <a-button 
              v-if="detailList.length > 0" 
              @click="handleClearAll" 
              style="margin-left: 8px;"
              icon="delete"
            >
              清空全部
            </a-button>
          </div>
          
          <!-- 按物料类型分组显示 -->
          <div v-if="detailList.length > 0">
            <div v-for="(materials, type) in groupedMaterials" :key="type" style="margin-bottom: 16px;">
              <a-divider orientation="left">
                <span style="font-weight: bold; color: #1890ff;">{{ materialTypeNames[type] || '未分类' }}</span>
                <a-tag color="blue" style="margin-left: 8px;">{{ materials.length }}项</a-tag>
              </a-divider>
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="materialColumns"
                :dataSource="materials"
                :pagination="false"
                :scroll="{ x: 1200 }"
              >
                <template slot="materialTypeSlot" slot-scope="text">
                  <j-dict-tag :value="text" dictCode="material_type"/>
                </template>
                
                <template slot="quantitySlot" slot-scope="text, record">
                  <a-input-number
                    v-model="record.quantity"
                    :precision="2"
                    :min="0"
                    style="width: 100px"
                @change="(value) => handleQuantityChange(record, value)"
              />
            </template>
            
            <template slot="locationSlot" slot-scope="text, record">
              <j-select-warehouse-location
                v-model="record.locationId"
                :warehouseId="record.warehouseId || (form ? form.getFieldValue('warehouseId') : null)"
                placeholder="请选择库位"
                style="width: 120px"
                @change="() => queryInventory(record)"
              />
            </template>
            
            
            <template slot="action" slot-scope="text, record, index">
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteDetail(record, index)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </div>
      </div>
      
      <div v-else style="text-align: center; margin: 50px 0;">
        <a-empty description="暂无物料明细，请添加物料" />
      </div>
    </a-card>
    </a-form>
  </a-spin>
    
    <!-- 添加明细弹窗 -->
    <detail-modal ref="detailModal" @ok="handleDetailModalOk"></detail-modal>
   
    <!-- 物料选择组件 - 隐藏输入框，只使用模态框功能 多选 -->
    <div style="position: absolute; left: -9999px; top: -9999px;">
      <j-select-material
        ref="materialSelector"
        :type="currentMaterialType"
        :title="getMaterialTitle()"
        :multiple="true"
        mode="multiple"
        @change="handleMaterialChange"
        @mounted="setupMaterialSelector"
        @cancel="handleMaterialSelectorCancel"
        @close="handleMaterialSelectorClose"
      />
    </div>
   
  </a-modal>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import AllocationPlanModal from './AllocationPlanModal'
  import { addOutbound, editOutbound, getOutboundById, getRequisitionByOrderNo, getInventoryByMaterial } from '@/api/wms/outbound'
  import DetailModal from './components/DetailModal'
  import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
  import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JSelectProductOrder from '@/components/jeecgbiz/JSelectProductOrder'
  import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'
  import pick from 'lodash.pick'
  import { v4 as uuidv4 } from 'uuid'
  
  export default {
    name: "OutboundModal",
    components: {
      DetailModal,
      AllocationPlanModal,
      JSelectWarehouse,
      JSelectWarehouseLocation,
      JDictSelectTag,
      JSelectProductOrder,
      JSelectMaterial
    },
    data () {
      return {
        title: "操作",
        width: 800,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: null,
        validatorRules: {
          outboundType: { rules: [{ required: true, message: '请选择出库类型!' }] },
          outboundDate: { rules: [{ required: true, message: '请选择出库日期!' }] },
          warehouseId: { rules: [{ required: true, message: '请选择仓库!' }] },
          orderId: { rules: [{ required: false }] },
          orderNo: { rules: [{ required: false }] },
          requisitionId: { rules: [{ required: false }] },
          remark: { rules: [{ required: false }] }
        },
        url: {
          add: "/wms/outbound/add",
          edit: "/wms/outbound/edit",
          queryById: "/wms/outbound/queryById"
        },
        detailList: [],
        outboundType: '4', // 默认为其他出库
        currentStep: 0,
        disableSubmit: false,
        
        // 物料表格列定义（移除库位字段）
        materialColumns: [
          {
            title: '物料类型',
            align: 'center',
            width: 100,
            dataIndex: 'materialType',
            scopedSlots: { customRender: 'materialTypeSlot' }
          },
          {
            title: '物料编码',
            align: 'center',
            width: 140,
            dataIndex: 'materialCode'
          },
          {
            title: '物料名称',
            align: 'center',
            width: 200,
            dataIndex: 'materialName'
          },
          {
            title: '规格',
            align: 'center',
            width: 150,
            dataIndex: 'specification'
          },
          {
            title: '颜色',
            align: 'center',
            width: 100,
            dataIndex: 'color'
          },
          {
            title: '数量',
            align: 'center',
            width: 120,
            dataIndex: 'quantity',
            scopedSlots: { customRender: 'quantitySlot' }
          },
          {
            title: '单位',
            align: 'center',
            width: 80,
            dataIndex: 'unit'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'action' }
          }
        ],
        currentMaterialType: '',
        requisitionOptions: [],
        warehouseNames: {},
        // 预览表格列
        previewColumns: [
          {
            title: '物料编码',
            align: 'center',
            dataIndex: 'materialCode'
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName'
          },
          {
            title: '规格',
            align: 'center',
            dataIndex: 'specification'
          },
          {
            title: '颜色',
            align: 'center',
            dataIndex: 'color'
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'quantity'
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit'
          },
          {
            title: '仓库',
            align: 'center',
            dataIndex: 'warehouseId'
          },
          {
            title: '库位',
            align: 'center',
            dataIndex: 'locationId'
          }
        ]
      }
    },
    computed: {
      formDisabled() {
        return false;
      },
      
      uploadAction() {
        return window._CONFIG['domianURL'] + '/sys/common/upload';
      },
      
      uploadHeaders() {
        let token = Vue.ls.get(ACCESS_TOKEN);
        return {
          'X-Access-Token': token
        };
      },
      
      // 按物料类型分组的物料列表
      groupedMaterials() {
        const groups = {};
        this.detailList.forEach(item => {
          const type = item.materialType || 'other';
          if (!groups[type]) {
            groups[type] = [];
          }
          groups[type].push(item);
        });
        return groups;
      },
      
      // 物料类型标题映射
      materialTypeNames() {
        return {
          '1': '型材',
          '2': '配件', 
          '3': '辅件',
          '4': '其他物料',
          '5': '余料',
          '6': '半料',
          'other': '未分类'
        };
      }
    },
    created() {
      // 在created生命周期中初始化表单
      this.form = this.$form.createForm(this);
      //每次打开模态框时，清空detailList
      this.detailList = [];
    },
    methods: {
      add () {
        this.resetModal();
        this.visible = true;
        this.title = "新增其他出库单";
        this.model = {};
        this.outboundType = '4'; // 固定为其他出库
        
        // 生成出库单号
        this.generateOutboundNo();
        
        // 加载仓库名称缓存
        this.loadWarehouseNames().catch((err) => {
          console.error('加载仓库数据失败:', err)
        });
      },
      edit (record) {
        this.resetModal();
        this.visible = true;
        this.title = "编辑出库单";
        this.model = Object.assign({}, record);
        
        if (this.model.id) {
          // 加载详情
          getOutboundById({id: this.model.id}).then(res => {
            if (res.success) {
              this.model = res.result;
              this.outboundType = this.model.outboundType;
              this.detailList = this.model.outboundDetailList || [];
              
              if (this.model.outboundVoucher) {
                this.fileList = [{
                  uid: '-1',
                  name: '出库凭证',
                  status: 'done',
                  url: this.model.outboundVoucher
                }];
              }
              
              this.$nextTick(() => {
                // 修改表单设置，添加orderName字段
                this.form.setFieldsValue(pick(this.model, 
                  'outboundType', 'outboundDate', 'warehouseId', 'orderId', 'orderNo', 'orderName', 'requisitionId', 'remark', 'outboundNo'
                ))
              });
              
              // 如果是生产领料类型，加载领料单选项
              if (this.outboundType == '2' && this.model.orderNo) {
                this.loadRequisitionOptions(this.model.orderNo);
              }
              
              // 加载仓库名称缓存
              this.loadWarehouseNames();
            }
          })
        }
      },
      resetModal() {
        if (this.form) {
          this.form.resetFields();
        }
        this.model = {};
        this.detailList = [];
        this.requisitionOptions = [];
        this.outboundType = '4'; // 固定为其他出库
        this.currentStep = 0;
        this.disableSubmit = false;
        
        // 清空物料选择器的选择状态
        this.clearMaterialSelector();
        
        // 设置出库日期默认值为当前日期
        const today = new Date();
        const formattedDate = today.getFullYear() + '-' + 
          String(today.getMonth() + 1).padStart(2, '0') + '-' + 
          String(today.getDate()).padStart(2, '0');
        
        this.$nextTick(() => {
          if (this.form) {
            this.form.setFieldsValue({
              'outboundDate': formattedDate,
              'outboundType': '4'
            });
          }
        });
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        if (!this.form) {
          this.$message.error('表单未初始化');
          return;
        }
        
        // 检查是否有物料明细
        if (this.detailList.length === 0) {
          this.$message.warning('请至少添加一个物料明细！');
          return;
        }
        
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let formData = Object.assign(this.model, values);
            
            // 固定设置出库类型为其他出库
            formData.outboundType = '4';
            
            // 添加明细列表 - 只传递物料信息和出库数量
            formData.outboundDetailList = this.detailList.map(item => ({
              materialId: item.materialId,
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialType: item.materialType,
              specification: item.specification,
              color: item.color,
              unit: item.unit,
              quantity: item.quantity
            }));
            
            let obj;
            if (!this.model.id) {
              obj = addOutbound(formData);
            } else {
              obj = editOutbound(formData);
            }
            
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
                // 清空物料选择器的选择状态
                that.clearMaterialSelector();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.detailList = [];
        // 清空物料选择器的选择状态
        this.clearMaterialSelector();
        this.close();
      },
      // 简化后不需要切换出库类型
      handleWarehouseChange(warehouseId) {
        // 当仓库改变时，清空所有明细的库位选择
        this.detailList.forEach(item => {
          item.warehouseId = warehouseId;
          item.locationId = null;
        });
      },
      generateOutboundNo() {
        // 生成当前日期时间字符串，格式为：年月日时分秒
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hour = String(now.getHours()).padStart(2, '0');
        const minute = String(now.getMinutes()).padStart(2, '0');
        const second = String(now.getSeconds()).padStart(2, '0');
        const dateStr = `${year}${month}${day}${hour}${minute}${second}`;

        // 生成随机数，用于区分同一时间创建的单据
        const randomNum = Math.floor(Math.random() * 1000)
          .toString()
          .padStart(3, '0');

        // 固定为其他出库前缀
        const outboundNoPrefix = 'QT';

        // 出库单号格式：出库类型前缀 + 年月日时分秒 + 3位随机数
        const outboundNo = `${outboundNoPrefix}${dateStr}${randomNum}`;

        // 设置出库单号
        if (this.form) {
          this.form.setFieldsValue({
            outboundNo: outboundNo
          });
        }
      },
      // 根据物料类型添加物料
      handleAddMaterial(materialType) {
        this.currentMaterialType = materialType;
        
        // 使用 $nextTick 确保 currentMaterialType 更新后再打开模态框
        this.$nextTick(() => {
          this.$refs.materialSelector.handleSearch();
        });
      },
      // 处理物料选择变化
      handleMaterialChange(selectedIds, selectedMaterials) {
        let addedCount = 0;
        let duplicateCount = 0;
        if (selectedMaterials && selectedMaterials.length > 0) {
          selectedMaterials.forEach(material => {
            const existingIndex = this.detailList.findIndex(item => item.materialId === material.id);
            if (existingIndex === -1) {
              const newDetail = {
                id: this.generateDetailId(),
                materialId: material.id,
                materialCode: material.materialCode,
                materialName: material.materialName,
                materialType: this.currentMaterialType,
                specification: material.specification,
                color: material.color,
                unit: material.unit,
                quantity: 0
              };
              this.detailList.push(newDetail);
              addedCount++;
            } else {
              duplicateCount++;
              //提示物料已存在
              this.$message.warning('物料"' + material.materialName + '"已存在');
            }
          });
        }
        
        // 清空物料选择器的选择状态，避免重复添加
        this.clearMaterialSelector();
      },
      
      // 获取物料类型标题
      getMaterialTitle() {
        const typeMap = {
          '1': '选择型材',
          '2': '选择配件', 
          '3': '选择辅件',
          '4': '选择其他物料',
          '5': '选择余料',
          '6': '选择半料'
        };
        return typeMap[this.currentMaterialType] || '选择物料';
      },
      
      // 清空所有物料
      handleClearAll() {
        this.$confirm({
          title: '确认清空',
          content: '确定要清空所有物料明细吗？',
          onOk: () => {
            this.detailList = [];
            this.$message.success('已清空所有物料明细');
          }
        });
      },
      
      
      // 生成明细ID
      generateDetailId() {
        return 'detail_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
      },

      // 处理数量变化
      handleQuantityChange(record, value) {
        record.quantity = value;
      },
      
      // 处理删除明细
      handleDeleteDetail(record, index) {
        this.detailList.splice(index, 1);
        this.$message.success('删除成功');
      },
      
      // 查询库存
      queryInventory(record) {
        if (!record.materialId || !record.locationId) {
          return;
        }
        // 这里可以添加库存查询逻辑
      },
      
      // 文件上传前处理
      beforeUpload(file) {
        const isImage = file.type.indexOf('image/') === 0;
        const isPdf = file.type === 'application/pdf';
        if (!isImage && !isPdf) {
          this.$message.error('只能上传图片或PDF文件!');
          return false;
        }
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$message.error('文件大小不能超过10MB!');
          return false;
        }
        return false; // 阻止自动上传
      },
      
      // 加载领料单选项（保留兼容性）
      loadRequisitionOptions(orderNo) {
        if (!orderNo) return;
        
        // 显示加载中
        this.$message.loading('正在加载领料单数据...');
        
        // 根据订单号查询领料单
        getRequisitionByOrderNo({orderNo: orderNo}).then(res => {
          if (res.success) {
            this.requisitionOptions = res.result.map(item => {
              return {
                value: item.id,
                label: item.requisitionNo
              };
            });
            
            if (this.requisitionOptions.length == 0) {
              this.$message.warning('该订单没有可用的领料单');
            } else {
              this.$message.success(`成功加载${this.requisitionOptions.length}个领料单`);
              
              // 默认选择第一个领料单
              if (this.requisitionOptions.length > 0) {
                const firstRequisition = this.requisitionOptions[0];
                if (this.form) {
                  this.form.setFieldsValue({
                    requisitionId: firstRequisition.value
                  });
                }
                
                // 加载领料单明细
                this.handleRequisitionChange(firstRequisition.value);
              }
            }
          } else {
            this.$message.warning(res.message || '获取领料单失败');
          }
        }).catch(err => {
          console.error('获取领料单异常:', err);
          this.$message.error('获取领料单异常');
        }).finally(() => {
          this.$message.destroy(); // 关闭loading提示
        });
      },
      handleRequisitionChange(value) {
        // 清空明细列表，等到点击下一步时再加载详细数据
        if (!value) {
          this.detailList = [];
        }
      },
      handleAddDetail() {
        const warehouseId = this.form ? this.form.getFieldValue('warehouseId') : null;
        this.$refs.detailModal.show({warehouseId: warehouseId});
      },
      handleDetailModalOk(detail) {
        // 生成唯一ID
        detail.id = uuidv4();
        this.detailList.push(detail);
      },
      handleDeleteDetail(record, index) {
        this.detailList.splice(index, 1);
      },
      handleImportDetail() {
        this.$message.info('导入功能开发中...');
      },
      beforeUpload(file) {
        this.fileList = [file];
        return false;
      },
      // 下一步
      nextStep() {
        this.validateCurrentStep()
          .then(() => {
            if (this.currentStep < 2) {
              this.currentStep++;
              
              // 如果进入到第三步，更新预览表格列定义
              if (this.currentStep == 2) {
                this.updatePreviewColumns();
              }
            }
          })
          .catch(err => {
            console.error('验证当前步骤失败:', err);
          });
      },
      // 上一步
      prevStep() {
        if (this.currentStep > 0) {
          this.currentStep--;
        }
      },
      // 验证当前步骤
      validateCurrentStep() {
        return new Promise((resolve, reject) => {
          // 根据当前步骤验证不同的字段
          let fieldsToValidate = [];

          switch (this.currentStep) {
            case 0: // 第一步：出库类型
              fieldsToValidate = ['outboundType', 'outboundDate', 'warehouseId'];
              if (this.outboundType == '2') {
                fieldsToValidate.push('orderId', 'requisitionId');
              }
              break;
            case 1: // 第二步：物料信息
              // 验证是否有明细
              if (this.detailList.length == 0) {
                this.$message.warning('请添加出库明细');
                return Promise.reject('请添加出库明细');
              }
              break;
            case 2: // 第三步：出库信息
              // 无需额外验证
              break;
          }

          if (!this.form) {
            reject(new Error('表单未初始化'));
            return;
          }
          this.form.validateFields(fieldsToValidate, (errors, values) => {
            if (errors) {
              reject(errors);
            } else {
              // 如果是生产领料类型，且从第一步到第二步，需要获取领料单详细数据
              if (this.outboundType == '2' && this.currentStep == 0) {
                const requisitionId = values.requisitionId;
                if (requisitionId) {
                  // 显示加载中
                  this.$message.loading('正在加载领料单详细数据...');
                  
                  // 调用接口获取领料单详细数据
                  getAction('/wms/requisition/queryById', {id: requisitionId}).then(res => {
                    if (res.success) {
                      // 将领料单明细转换为出库单明细
                      const requisitionDetail = res.result;
                      
                      // 保存领料单信息到model中，以便后续使用
                      this.model.requisition = requisitionDetail.requisition || {};
                      
                      // 获取优化软件类型
                      const optimizationSoftwareType = this.model.requisition.optimizationSoftwareType || 0;
                      
                      // 清空当前明细列表
                      this.detailList = [];
                      
                      // 处理型材列表 (profileList)
                      const profileList = requisitionDetail.profileList || [];
                      profileList.forEach(item => {
                        const detail = {
                          id: uuidv4(),
                          materialType: '1', // 型材
                          materialCode: item.profileCode,
                          materialName: item.profileName,
                          specification: item.specification || ((item.length || '-' )+ '/' + (item.width || '-' )+ '/' + (item.height || '-' )),//长宽高数据为空时使用-，通过/分割
                          color: item.color,
                          unit: item.unit || '根',
                          warehouseId: this.form ? this.form.getFieldValue('warehouseId') : null,
                          locationId: item.locationId || '',
                          remark: item.remark || ''
                        };
                        
                        // 根据优化软件类型设置不同的字段
                        if (optimizationSoftwareType == 0) {
                          detail.quantity = item.quantity;
                        } else {
                          detail.lengthQuantity = item.lengthQuantity || item.quantity;
                        }
                        
                        this.detailList.push(detail);
                      });
                      
                      // 处理配件列表 (accessoryList)
                      const accessoryList = requisitionDetail.accessoryList || [];
                      accessoryList.forEach(item => {
                        const detail = {
                          id: uuidv4(),
                          materialType: '2', // 配件
                          materialCode: item.accessoryCode,
                          materialName: item.accessoryName,
                          specification: item.specification,
                          color: '',
                          unit: item.unit || '个',
                          warehouseId: this.form ? this.form.getFieldValue('warehouseId') : null,
                          locationId: item.locationId || '',
                          remark: item.remark || ''
                        };
                        
                        // 根据优化软件类型设置不同的字段
                        if (optimizationSoftwareType == 0) {
                          detail.quantity = item.quantity;
                        } else {
                          detail.lengthQuantity = item.lengthQuantity || item.quantity;
                        }
                        
                        this.detailList.push(detail);
                      });
                      
                      this.$message.success(`成功加载领料单详细数据，共${this.detailList.length}条明细`);
                      resolve(values);
                    } else {
                      this.$message.warning(res.message || '获取领料单详细数据失败');
                      reject(new Error('获取领料单详细数据失败'));
                    }
                  }).catch(err => {
                    console.error('获取领料单详细数据异常:', err);
                    this.$message.error('获取领料单详细数据异常');
                    reject(err);
                  }).finally(() => {
                    this.$message.destroy(); // 关闭loading提示
                  });
                } else {
                  resolve(values);
                }
              } else {
                resolve(values);
              }
            }
          });
        });
      },
      // 获取出库类型名称
      getOutboundTypeName() {
        const outboundType = this.outboundType;
        switch (outboundType) {
          case '1':
            return '销售出库';
          case '2':
            return '生产领料';
          case '3':
            return '调拨出库';
          case '4':
            return '其他出库';
          default:
            return '';
        }
      },
      // 获取领料单号
      getRequisitionNo() {
        const requisitionId = this.form ? this.form.getFieldValue('requisitionId') : null;
        if (!requisitionId) return '';

        // 从已加载的领料单选项中查找对应的领料单号
        const option = this.requisitionOptions.find(o => o.value == requisitionId);
        return option ? option.label : '';
      },
      // 获取仓库名称
      getWarehouseName() {
        const warehouseId = this.form.getFieldValue('warehouseId');
        if (!warehouseId) return '';

        // 如果仓库名称缓存已存在，直接使用
        if (this.warehouseNameMap && this.warehouseNameMap[warehouseId]) {
          return this.warehouseNameMap[warehouseId];
        }

        // 否则返回空字符串，等待异步加载
        return '';
      },
      // 加载仓库名称缓存
      loadWarehouseNames() {
        // 获取所有仓库信息
        return new Promise((resolve, reject) => {
          getAction('/wms/warehouse/listAll')
            .then((res) => {
              if (res.success && res.result) {
                const warehouseList = res.result;
                this.warehouseList = warehouseList; // 保存仓库列表

                const warehouseMap = {};
                warehouseList.forEach((warehouse) => {
                  warehouseMap[warehouse.id] = warehouse.warehouseName;
                });

                // 更新仓库名称缓存
                this.warehouseNameMap = warehouseMap;

                console.log('已加载仓库数据:', warehouseList.length, '个仓库');
                resolve(warehouseList);
              } else {
                console.error('加载仓库数据失败:', res.message || '未知错误');
                this.$message.error('加载仓库数据失败，请刷新页面重试');
                reject(new Error(res.message || '加载仓库数据失败'));
              }
            })
            .catch((err) => {
              console.error('加载仓库数据异常:', err);
              this.$message.error('加载仓库数据异常，请刷新页面重试');
              reject(err);
            });
        });
      },
      // 根据物料类型获取明细列表
      getDetailsByType(type) {
        if (!this.detailList || !Array.isArray(this.detailList)) {
          return [];
        }
        return this.detailList.filter(item => item.materialType == type);
      },
      // 根据物料类型获取列定义
      getColumnsForType(type) {
        let columns = [
          {
            title: '物料编码',
            align: 'center',
            width: 140,
            dataIndex: 'materialCode'
          },
          {
            title: '物料名称',
            align: 'center',
            width: 180,
            dataIndex: 'materialName'
          },
          {
            title: '规格',
            align: 'center',
            width: 180,
            dataIndex: 'specification'
          },
          {
            title: '颜色',
            align: 'center',
            width: 140,
            dataIndex: 'color'
          }
        ];
        
        // 获取领料单信息
        const requisitionId = this.form.getFieldValue('requisitionId');
        const requisition = this.requisitionOptions.find(item => item.value == requisitionId);
        
        // 从model中获取optimizationSoftwareType，默认为0
        let optimizationSoftwareType = 0;
        if (this.model && this.model.requisition) {
          optimizationSoftwareType = this.model.requisition.optimizationSoftwareType || 0;
        }
        
        // 根据optimizationSoftwareType决定显示哪个字段
        if (optimizationSoftwareType == 0) {
          columns.push({
            title: '数量',
            align: 'center',
            width: 120,
            dataIndex: 'quantity',
            scopedSlots: { customRender: 'quantitySlot' }
          });
        } else {
          columns.push({
            title: '长度/数量',
            align: 'center',
            width: 120,
            dataIndex: 'lengthQuantity',
            scopedSlots: { customRender: 'lengthQuantitySlot' }
          });
        }
        
        columns.push({
          title: '单位',
          align: 'center',
          width: 100,
          dataIndex: 'unit'
        });
        
        // 添加出库方案列
        columns.push(
          {
            title: '出库方案',
            align: 'center',
            width: 120,
            dataIndex: 'outboundPlan',
            scopedSlots: { customRender: 'outboundPlanSlot' }
          }
        );
        
        // 如果不是生产领料模式，添加操作列
        if (this.outboundType !== '2') {
          columns.push({
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 100,
            scopedSlots: { customRender: 'action' }
          });
        }

        return columns;
      },
      
      // 更新预览表格列定义
      updatePreviewColumns() {
        // 获取优化软件类型
        let optimizationSoftwareType = 0;
        if (this.model && this.model.requisition) {
          optimizationSoftwareType = this.model.requisition.optimizationSoftwareType || 0;
        }
        
        // 基础列
        this.previewColumns = [
          {
            title: '物料编码',
            align: 'center',
            width: 140,
            dataIndex: 'materialCode'
          },
          {
            title: '物料名称',
            align: 'center',
            width: 180,
            dataIndex: 'materialName'
          },
          {
            title: '规格',
            align: 'center',
            width: 180,
            dataIndex: 'specification'
          },
          {
            title: '颜色',
            align: 'center',
            width: 140,
            dataIndex: 'color'
          }
        ];
        
        // 根据优化软件类型添加不同的字段
        if (optimizationSoftwareType == 0) {
          this.previewColumns.push({
            title: '数量',
            align: 'center',
            width: 120,
            dataIndex: 'quantity',
            scopedSlots: { customRender: 'quantitySlot' }
          });
        } else {
          this.previewColumns.push({
            title: '长度/数量',
            align: 'center',
            width: 120,
            dataIndex: 'lengthQuantity',
            scopedSlots: { customRender: 'lengthQuantitySlot' }
          });
        }
        
        // 添加其他列
        this.previewColumns.push(
          {
            title: '单位',
            align: 'center',
            width: 100,
            dataIndex: 'unit'
          },
          {
            title: '出库方案',
            align: 'center',
            width: 120,
            dataIndex: 'outboundPlan',
            scopedSlots: { customRender: 'outboundPlanSlot' }
          }
        );
      },
      handleMaterialOk() {
        if (this.selectedMaterials && this.selectedMaterials.length > 0) {
          this.selectedMaterials.forEach(material => {
            const detail = {
              id: uuidv4(),
              materialType: this.currentMaterialType, // 使用当前选择的物料类型
              materialCode: material.materialCode,
              materialName: material.materialName,
              specification: material.specification,
              color: material.color,
              unit: material.unit || this.getDefaultUnit(),
              warehouseId: this.form.getFieldValue('warehouseId'),
              locationId: material.locationId || '',
              remark: material.remark
            };
            // 根据优化软件类型设置不同的字段
            if (this.model.requisition && this.model.requisition.optimizationSoftwareType == 0) {
              detail.quantity = material.quantity || 1;
            } else {
              detail.lengthQuantity = material.lengthQuantity || material.quantity || 1;
            }
            this.detailList.push(detail);
          });
          this.materialModalVisible = false;
        }
      },
      handleMaterialCancel() {
        this.materialModalVisible = false;
      },
      // 设置物料选择器
      setupMaterialSelector() {
        // 这个方法用于处理物料选择器的mounted事件
        console.log('Material selector mounted');
      },
      
      // 清空物料选择器的选择状态
      clearMaterialSelector() {
        if (this.$refs.materialSelector) {
          // 清空选择状态 - 直接重置组件的内部状态
          this.$refs.materialSelector.selectedRowKeys = [];
          this.$refs.materialSelector.selectedMaterialKeys = [];
          this.$refs.materialSelector.selectedMaterialNames = '';
          this.$refs.materialSelector.selectedMaterials = [];
        }
      },
      
      // 处理物料选择器取消事件
      handleMaterialSelectorCancel() {
        // 当用户点击取消或关闭物料选择器时，清空选择状态
        this.clearMaterialSelector();
      },
      
      // 处理物料选择器关闭事件
      handleMaterialSelectorClose() {
        // 当物料选择器关闭时，清空选择状态
        this.clearMaterialSelector();
      },
      // 获取物料选择弹窗标题
      getMaterialTitle() {
        switch(this.currentMaterialType) {
          case '1': return '选择型材';
          case '2': return '选择配件';
          case '3': return '选择辅件';
          case '4': return '选择其他物料';
          case '5': return '选择余料';
          case '6': return '选择半料';
          default: return '选择物料';
        }
      },
      // 获取默认单位
      getDefaultUnit() {
        switch(this.currentMaterialType) {
          case '1': return '根';
          case '2': 
          case '3': return '个';
          case '4':
          case '5':
          case '6': return '件';
          default: return '个';
        }
      },
      // 处理数量变化
      handleQuantityChange(record, value) {
        if (value === null || value === undefined) {
          record.quantity = 0;
        } else {
          record.quantity = value;
        }
      },
      // 处理长度/数量变化
      handleLengthQuantityChange(record, value) {
        if (value === null || value === undefined) {
          record.lengthQuantity = 0;
        } else {
          record.lengthQuantity = value;
        }
      },
      // 数量输入框失去焦点时查询库存
      handleQuantityBlur(record) {
        if (record.quantity === null || record.quantity === undefined || record.quantity === '') {
          record.quantity = 0;
          return;
        }
        if (record.quantity < 0) {
          record.quantity = 0;
          return;
        }
        this.queryInventory(record);
      },
      // 长度/数量输入框失去焦点时查询库存
      handleLengthQuantityBlur(record) {
        if (record.lengthQuantity === null || record.lengthQuantity === undefined || record.lengthQuantity === '') {
          record.lengthQuantity = 0;
          return;
        }
        if (record.lengthQuantity < 0) {
          record.lengthQuantity = 0;
          return;
        }
        this.queryInventory(record);
      },
      // 查询库存
      queryInventory(record) {
        if (!record.materialCode) {
          // 如果没有物料编码，不进行查询
          return;
        }
        
        // 计算所需数量
        const requiredQuantity = record.quantity || record.lengthQuantity || 0;
        if (requiredQuantity <= 0) {
          // 如果数量为0或负数，清空库存选项
          record.availableInventoryOptions = [];
          record.selectedInventoryId = null;
          return;
        }

        this.$message.loading('正在查询库存...');
        
        // 使用新的库存查询API
        this.$http.get('/wms/inventory/queryAvailableInventory', {
          params: {
            materialCode: record.materialCode,
            materialType: record.materialType,
            requiredQuantity: requiredQuantity
          }
        }).then(res => {
          if (res.data.success) {
            const inventoryList = res.data.result || [];
            
            if (inventoryList.length === 0) {
              this.$message.warning('该物料没有可用库存');
              record.availableInventoryOptions = [];
              record.selectedInventoryId = null;
              return;
            }
            
            // 转换为下拉选项格式
            record.availableInventoryOptions = inventoryList.map(inv => ({
              value: inv.id,
              label: `${inv.warehouseName} - ${inv.locationName} (库存: ${inv.quantity} ${inv.unit})`,
              warehouseName: inv.warehouseName,
              locationName: inv.locationName,
              quantity: inv.quantity,
              unit: inv.unit,
              sufficient: inv.sufficient,
              warehouseId: inv.warehouseId,
              locationId: inv.locationId,
              inventoryId: inv.id
            }));
            
            // 如果只有一个选项且库存充足，自动选择
            if (inventoryList.length === 1 && inventoryList[0].sufficient) {
              record.selectedInventoryId = inventoryList[0].id;
              this.handleInventorySelect(record, inventoryList[0].id);
            }
            
            this.$message.success(`找到 ${inventoryList.length} 个可用库存`);
          } else {
            this.$message.warning(res.data.message || '查询库存失败');
            record.availableInventoryOptions = [];
            record.selectedInventoryId = null;
          }
        }).catch(err => {
          console.error('查询库存异常:', err);
        }).finally(() => {
          this.$message.destroy();
        });
      },
      
      // 显示出库方案
      showOutboundPlan(record) {
        if (!record.materialCode) {
          this.$message.warning('请先选择物料');
          return;
        }
        
        if (!record.quantity || record.quantity <= 0) {
          this.$message.warning('请先输入出库数量');
          return;
        }
        
        // 设置当前记录
        this.currentPlanRecord = record;
        
        // 显示加载状态并查询出库方案
        this.$message.loading('正在查询出库方案...');
        
        this.$http.get('/wms/inventory/queryAvailableInventory', {
          params: {
            materialCode: record.materialCode,
            materialType: record.materialType,
            requiredQuantity: record.quantity
          }
        }).then(res => {
          if (res.success) {
            const planList = res.result || [];
            this.currentOutboundPlan = planList;
            
            // 更新记录的出库方案
            record.outboundPlan = planList;
            record.hasOutboundPlan = planList.length > 0;
            
            if (planList.length === 0) {
              this.$message.warning('该物料没有可用库存');
              this.isInsufficientStock = true;
              this.insufficientStockMessage = '该物料没有可用库存';
              this.canConfirmPlan = false;
            } else {
              // 检查库存是否充足
              const totalAvailable = planList.reduce((sum, item) => sum + (item.quantity || 0), 0);
              if (totalAvailable < record.quantity) {
                this.isInsufficientStock = true;
                this.insufficientStockMessage = `库存不足！需求数量: ${record.quantity} ${record.unit}，可用数量: ${totalAvailable} ${record.unit}`;
                this.canConfirmPlan = false;
                this.$message.warning(`库存不足！需要 ${record.quantity} ${record.unit}，但只有 ${totalAvailable} ${record.unit} 可用`);
              } else {
                this.isInsufficientStock = false;
                this.insufficientStockMessage = '';
                this.canConfirmPlan = true;
                this.$message.success(`出库方案已生成，涉及 ${planList.length} 个库位`);
              }
            }
            
            // 打开抽屉显示方案
            this.outboundPlanVisible = true;
          } else {
            this.$message.error(res.message || '查询出库方案失败');
          }
        }).catch(err => {
          console.error('查询出库方案异常:', err);
          this.$message.error('查询出库方案异常');
        }).finally(() => {
          this.$message.destroy();
        });
      },
      
      // 查询出库方案
      queryOutboundPlan(record) {
        const requiredQuantity = record.quantity || record.lengthQuantity || 0;
        
        this.$message.loading('正在查询出库方案...');
        
        this.$http.get('/wms/inventory/queryAvailableInventory', {
          params: {
            materialCode: record.materialCode,
            materialType: record.materialType,
            requiredQuantity: requiredQuantity
          }
        }).then(res => {
          if (res.data.success) {
            const planList = res.data.result || [];
            this.currentOutboundPlan = planList;
            
            // 检查是否库存不足
            if (planList.length > 0 && planList[0].insufficientStock) {
              this.isInsufficientStock = true;
              this.insufficientStockMessage = `库存不足！需求数量: ${planList[0].requiredQuantity}，可用数量: ${planList[0].totalAvailableQuantity}，是否确认按可用数量出库？`;
              this.canConfirmPlan = false; // 需要用户确认
            } else {
              this.isInsufficientStock = false;
              this.insufficientStockMessage = '';
              this.canConfirmPlan = true;
            }
            
            if (planList.length === 0) {
              this.$message.warning('该物料没有可用库存');
            } else {
              this.$message.success(`已生成出库方案，涉及 ${planList.length} 个库位`);
            }
          } else {
            this.$message.error(res.data.message || '查询出库方案失败');
            this.currentOutboundPlan = [];
          }
        }).catch(err => {
          console.error('查询出库方案异常:', err);
          this.$message.error('查询出库方案异常');
          this.currentOutboundPlan = [];
        }).finally(() => {
          this.$message.destroy();
        });
      },
      
      // 关闭出库方案抽屉
      closeOutboundPlan() {
        this.outboundPlanVisible = false;
        this.currentOutboundPlan = [];
        this.currentPlanRecord = null;
        this.isInsufficientStock = false;
        this.insufficientStockMessage = '';
        this.canConfirmPlan = true;
      },
      
      // 确认出库方案
      confirmOutboundPlan() {
        if (this.isInsufficientStock && !this.canConfirmPlan) {
          // 显示确认对话框
          this.$confirm({
            title: '库存不足确认',
            content: this.insufficientStockMessage,
            okText: '确认出库',
            cancelText: '取消',
            onOk: () => {
              this.applyOutboundPlan();
            }
          });
        } else {
          this.applyOutboundPlan();
        }
      },
      
      // 应用出库方案
      applyOutboundPlan() {
        if (!this.currentPlanRecord || this.currentOutboundPlan.length === 0) {
          return;
        }
        
        // 将出库方案应用到当前记录
        this.currentPlanRecord.outboundPlanList = this.currentOutboundPlan;
        this.currentPlanRecord.hasOutboundPlan = true;
        
        // 如果是库存不足的情况，更新实际出库数量
        if (this.isInsufficientStock && this.currentOutboundPlan[0]) {
          const actualQuantity = this.currentOutboundPlan[0].totalAvailableQuantity;
          if (this.currentPlanRecord.quantity !== undefined) {
            this.currentPlanRecord.quantity = actualQuantity;
          }
          if (this.currentPlanRecord.lengthQuantity !== undefined) {
            this.currentPlanRecord.lengthQuantity = actualQuantity;
          }
        }
        
        this.$message.success('出库方案已确认');
        this.closeOutboundPlan();
      }
    }
  }
</script>

<style scoped>
.material-title {
  font-size: 16px;
  font-weight: 500;
  padding: 4px 10px;
  border-radius: 4px;
}

.material-title-profile {
  color: #1890ff;
  background-color: #e6f7ff;
}

.material-title-accessory {
  color: #52c41a;
  background-color: #f6ffed;
}

.material-title-auxiliary {
  color: #722ed1;
  background-color: #f9f0ff;
}

.material-title-other {
  color: #fa8c16;
  background-color: #fff7e6;
}

.material-title-surplus {
  color: #13c2c2;
  background-color: #e6fffb;
}

.material-title-semi {
  color: #eb2f96;
  background-color: #fff0f6;
}

/* 表格行样式 */
.profile-row >>> td {
  background-color: #e6f7ff;
}
.profile-row:hover >>> td {
  background-color: #bae7ff !important;
}

.accessory-row >>> td {
  background-color: #f6ffed;
}
.accessory-row:hover >>> td {
  background-color: #b7eb8f !important;
}

.auxiliary-row >>> td {
  background-color: #f9f0ff;
}
.auxiliary-row:hover >>> td {
  background-color: #d3adf7 !important;
}

.other-row >>> td {
  background-color: #fff7e6;
}
.other-row:hover >>> td {
  background-color: #ffd591 !important;
}

.surplus-row >>> td {
  background-color: #e6fffb;
}
.surplus-row:hover >>> td {
  background-color: #87e8de !important;
}

.semi-row >>> td {
  background-color: #fff0f6;
}
.semi-row:hover >>> td {
  background-color: #ffadd2 !important;
}

/* 修复表头和表体对齐问题 */
.ant-table >>> .ant-table-header-column {
  width: 100%;
}

.ant-table >>> .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  margin-right: 0 !important;
  padding-right: 0 !important;
  overflow: hidden;
}

.ant-table >>> .ant-table-fixed-header .ant-table-body {
  overflow-x: auto !important;
}

.ant-table >>> .ant-table-thead > tr > th,
.ant-table >>> .ant-table-tbody > tr > td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style> 